# -*- encoding : utf-8 -*-
class User < ActiveRecord::Base
  EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
  validates :card_id, :presence => true, :on => :create 
  validates :card_id, :uniqueness => true
  validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
  validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
  validates :password, :presence => true, :confirmation => true
  validates_length_of :password, :in => 6..20, :on => :create
  validates :reader_id, :presence => true

  attr_accessible :username, :email, :password, :password_confirmation, :fullname, :phone, :faculty_id, :card_id, :reader_id, :role_id

  before_save :encrypt_password
  after_save :clear_password
  
  def encrypt_password
    # only encrypt when create new user
    if !User.find_by_username(self.username)
      if password.present?
        self.salt = BCrypt::Engine.generate_salt
        self.password = BCrypt::Engine.hash_secret(password, salt)
      end
    end
  end
  
  def clear_password
    self.password = nil
  end
  
  def self.authenticate(username_or_email = '', login_password = '')
    if (EMAIL_REGEX.match(username_or_email))
      user = User.find_by_email(username_or_email)
    else
      user = User.find_by_username(username_or_email)
    end
    
    if(user && user.match_password(login_password))
      return user
    else
      return false
    end
  end
  
  def match_password(login_password = '')
    return self.password == BCrypt::Engine.hash_secret(login_password, self.salt)
  end
  
  belongs_to :role
  belongs_to :faculty
  
  has_many :punishments
  has_many :book_borrows
  has_many :book_reserves
end
